package com.neucloud.da.edgeside.model.utils;

import org.mozilla.universalchardet.UniversalDetector;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class EncodingDetector {

    public static String detectEncoding(InputStream inputStream) throws IOException {
        byte[] buf = new byte[4096];
        UniversalDetector detector = new UniversalDetector(null);
        int nread;

        while ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }

        detector.dataEnd();

        String encoding = detector.getDetectedCharset();
        detector.reset();

        if (encoding == null || encoding.isEmpty()) {
            encoding = StandardCharsets.UTF_8.name(); // Default to UTF-8 if no encoding detected
        }

        inputStream.close(); // Ensure the InputStream is closed
        return encoding;
    }

    public static void main(String[] args) {
        // Example usage: detect the encoding of a file
        try (InputStream inputStream = EncodingDetector.class.getResourceAsStream("Test.class")) {
            System.out.println(inputStream);
            String detectedEncoding = detectEncoding(inputStream);
            System.out.println("Detected Encoding: " + detectedEncoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
